package mspbots.timedoctor.client.core.api.v2;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.timedoctor.client.config.RabbitConfiguration;
import mspbots.timedoctor.client.core.api.BaseApiService;
import mspbots.timedoctor.client.core.api.ResultMessageModel;
import mspbots.timedoctor.client.core.api.constant.API;
import mspbots.timedoctor.client.core.listener.SyncTimeDTO;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * data.connector.timedoctor.api.CompaniesService
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/3/25
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class UsersV2Service extends BaseApiService {

    private static Map api_status = new ConcurrentHashMap();
    private final WorkLogsV2Service workLogsV2Service;

    public void async(String syncId, Long tenant, String companyId) {
        final long start = System.nanoTime();
        this.doctorV2Client.get(API.V2_USERS_ALL, Map.of("tenantId", tenant, "company", companyId))
                .map(jsonNode -> jsonNode.get("data"))
                .doOnNext(jsonNode -> workLogsV2Service.async(syncId, tenant, companyId, jsonNode))
                .subscribe(result -> {
                            this.messagingTemplate.convertAndSend(RabbitConfiguration.DATA_CONNECTOR_TIMEDOCTOR,
                                    "timedoctor-users-key",
                                    ResultMessageModel.builder().action(ResultMessageModel.MessageModelAction.ADD)
                                            .type(ResultMessageModel.MessageModelType.USERS)
                                            .sendTime(LocalDateTime.now())
                                            .entity(result)
                                            .tenantId(tenant)
                                            .build());

                            long milliseconds = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
                            log.debug("Time taken {}: {}  milliseconds.", "Completed", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start));
                            this.messagingTemplate.convertAndSend("timedoctor.sync.time", SyncTimeDTO.builder()
                                    .api(API.V2_USERS_ALL)
                                    .last_time(LocalDateTime.now())
                                    .milliseconds(milliseconds)
                                    .status("Completed")
                                    .msg("Success")
                                    .tenantId(tenant)
                                    .build()
                            );

                            this.sendLog(syncId, tenant, milliseconds, API.V2_USERS_ALL, SUCCESS_CODE, "", result);
                        }
                        , err -> {
                            long milliseconds = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
                            log.error("Companies sync data error, msg:{}", err.getMessage());
                            this.messagingTemplate.convertAndSend("timedoctor.sync.time", SyncTimeDTO.builder()
                                    .api(API.V2_USERS_ALL)
                                    .last_time(LocalDateTime.now())
                                    .milliseconds(milliseconds)
                                    .status("Error")
                                    .msg(err.getMessage())
                                    .tenantId(tenant)
                                    .build()
                            );

                            this.sendLog(syncId, tenant, milliseconds, API.V2_USERS_ALL, FAIL_CODE, err.getMessage(), null);
                        });
    }


}
